﻿using Dto;
using IBLL;
using IDAL;
using MD5Hash;
using Model;

namespace BLL
{
    public class MemberBLL : IMemberBLL
    {
        public MemberBLL(IMemberDAL<MemberModel>dal,IMemberDAL<MemberLevelModel>mdal)
        {
            Dal = dal;
            Mdal = mdal;
        }

        public IMemberDAL<MemberModel> Dal { get; }
        public IMemberDAL<MemberLevelModel> Mdal { get; }

        public async Task<int> AddMember(MemberModel member)
        {
            //唯一性验证
            var s=Dal.GetMembersAsync().Any(a=>a.Name==member.Name);
            member.Password=member.Password.GetMD5();
            if (!s)
            {
                return await Dal.AddMemberAsync(member);
            }
            else 
            {
                return -1;
            }
            
        }

        public MemberModel Ft(int id)
        {
            return Dal.GetMembersAsync().FirstOrDefault(a => a.Id == id);
        }

        public GetMemberPageDto GetMemberPage(int pageindex, int pagesize)
        {
            var a = Dal.GetMembersAsync();
            var b=Mdal.GetMembersAsync();
            var sql = from c in a
                      join d in b on c.LevelId equals d.Id
                      select new 
                      {
                          c.Id,
                          c.Name,
                          c.LevelId,
                          c.Img,
                          d.LevelName
                      };
            int s = sql.Count();
            var m= sql.OrderBy(x => x.Id).Skip((pageindex - 1) * pagesize).Take(pagesize).ToList();
            return new GetMemberPageDto { Count = s, Members = m };
        }

        public async Task<int> UpdateMember(MemberModel member)
        {
            var s=Dal.GetMembersAsync().Any(a=>a.Name==member.Name && a.Id !=member.Id);
            if (!s)
            {
                member.UpdateDate = DateTime.Now;
                return await Dal.UpdateMemberAsync(member);
            }
            else 
            {
                return -1;
            }
            
            
        }
    }
}
